package com.losalpes.catalog;

import com.losalpes.persistence.entity.Mueble;
import com.losalpes.persistence.entity.TipoMueble;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import org.richfaces.event.UploadEvent;
import org.richfaces.model.UploadItem;

/**
 *
 * @author Camilo Alvarez
 */
public class CatalogBean {
    @EJB
    private ICatalogService catalogService;
    private Mueble mueble = new Mueble();

    public CatalogBean() {       
    }

    public void listener(UploadEvent event) throws Exception {
        System.out.println("Listener " + event);
        UploadItem item = event.getUploadItem();
        mueble.setFoto(item.getData());
    }

    public void paint(OutputStream stream, Object object) throws IOException {
        System.out.println("pintando ");
        if (mueble.getFoto() != null) {
            stream.write(mueble.getFoto());
        } else {
            FacesContext fc = FacesContext.getCurrentInstance();
            ServletContext sc = (ServletContext) fc.getExternalContext().getContext();
            InputStream is = sc.getResourceAsStream("img/empty.jpg");
            int lectura = 0;
            while ((lectura = is.available()) != 0) {
                byte[] leido = new byte[lectura];
                is.read(leido, 0, lectura);
                stream.write(leido);
            }
            is.close();
        }
    }

    public long getTimeStamp() {
        return System.currentTimeMillis();
    }

    public List getMuebles() {
        return catalogService.findAllMuebles();
    }

    public SelectItem[] getTiposMuebles() {
        TipoMueble[] tipos = TipoMueble.values();
        SelectItem[] sitems = new SelectItem[tipos.length];
        for (int i = 0; i < sitems.length; i++) {
            sitems[i] = new SelectItem(tipos[i]);
        }
        return sitems;
    }

    public String add() {
        catalogService.add(mueble);
        mueble = new Mueble();
        return null;
    }

    public Mueble getMueble() {
        return mueble;
    }

    public void setMueble(Mueble cMueble) {
        System.out.println("Set Mueble " + cMueble.getNombre());
        this.mueble = cMueble;
    }

    public String limpiarCampos() {
        this.mueble = new Mueble();
        return "regresar";
    }

    public void eliminarMueble() {
        System.out.println("Eliminar Mueble " + mueble.getNombre());
        catalogService.eliminarMueble(mueble);
        limpiarCampos();
    }

    public void actualizarMueble() {
        catalogService.actualizarMueble(mueble);
        limpiarCampos();
    }
}
